<?php

namespace App\Kuafu\Shop\Service;

use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Nsq\Enum\NsqCodeEnum;
use App\Kuafu\Shop\Enum\AreaCodeEnum;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\Shop\Model\AreaModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Model\ShopAttributeCategoryModel;
use App\Kuafu\Shop\Model\ShopAttributeMappingModel;
use App\Kuafu\Shop\Model\ShopAttributeModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ShopAttributeService extends BaseService
{

    /**
     * 属性值列表
     * @param bool $isGetEdit 是否获取可编辑的属性
     * @return array
     */
    public static function getAttributeList(bool $isGetEdit = false): array
    {
        return ShopAttributeCategoryModel::query()
                                         ->with(['attributeRel'])
                                         ->when($isGetEdit, function ($query) {
                                             $query->where('isEdit', ShopAttributeCategoryModel::CAN_EDIT);
                                         })
                                         ->get()
                                         ->map(function ($item) {
                                             return [
                                                 'id'       => $item->id,
                                                 'name'     => $item->name,
                                                 'type'     => $item->type,
                                                 'typeText' => ShopAttributeCategoryModel::TYPE_TEXT_MAPPING[$item->type] ?? '',
                                                 'value'    => $item->attributeRel ?? [],
                                             ];
                                         })->toArray();
    }


    /**
     * 属性值详情
     * @param int $id
     * @return array
     */
    public static function getAttributeInfo(int $id): array
    {
        return ShopAttributeCategoryModel::query()
                                         ->with(['attributeRel'])
                                         ->where('id', $id)
                                         ->get()
                                         ->map(function ($item) {
                                             return [
                                                 'id'       => $item->id,
                                                 'name'     => $item->name,
                                                 'type'     => $item->type,
                                                 'typeText' => ShopAttributeCategoryModel::TYPE_TEXT_MAPPING[$item->type] ?? '',
                                                 'value'    => $item->attributeRel ?? [],
                                             ];
                                         })->toArray()[0] ?? [];
    }

    /**
     * 属性值编辑
     * @param int $id
     * @param array $data
     * @param int $rmsUserId
     * @return array
     * @throws ShopException
     */
    public static function updateAttribute(int $id, array $data, int $rmsUserId): array
    {

        // 和之前id对比判断是否删除
        $oldIds  = ShopAttributeModel::query()->where('categoryId', $id)->pluck('id')->toArray();
        $postIds = collect($data)->where('id', '>', 0)->pluck('id')->toArray();
        $delIds  = array_diff($oldIds, $postIds);

        $updateData = $addData = [];
        foreach ($data as $v) {
            if (!$v['name']) {
                continue;
            }
            if ($v['id']) {// 查询之前的数据
                $info = ShopAttributeModel::query()
                                          ->where('categoryId', $id)
                                          ->where('id', $v['id'])
                                          ->first();
                if ($info) {
                    if ($info->name != $v['name']) {
                        $updateData[] = [
                            'id'   => $v['id'],
                            'name' => $v['name'],
                        ];
                    }
                } else {
                    $addData[] = [
                        'categoryId'   => $id,
                        'name'         => $v['name'],
                        'createdByUid' => $rmsUserId,
                        'createdAt'    => time(),
                    ];
                }
            } else { // 根据名称判断是否存在
                $info = ShopAttributeModel::query()
                                          ->where('categoryId', $id)
                                          ->where('name', $v['name'])
                                          ->first();
                if ($info) {
                    if (in_array($info->id, $delIds)) {
                        $delIds = array_diff($delIds, [$info->id]);
                    }
                } else {
                    $addData[] = [
                        'categoryId'   => $id,
                        'name'         => $v['name'],
                        'createdByUid' => $rmsUserId,
                        'createdAt'    => time(),
                    ];
                }
            }
        }

        DB::beginTransaction();
        try {

            // 新增数据
            if ($addData) {
                ShopAttributeModel::query()->insert($addData);
            }

            // 编辑数据
            if ($updateData) {
                foreach ($updateData as $v) {
                    ShopAttributeModel::updateById($v['id'],
                        [
                            'name'         => $v['name'],
                            'updatedByUid' => $rmsUserId,
                        ]);
                }
            }

            // 删除数据
            if ($delIds) {
                foreach ($delIds as $id) {

                    // 门店属性值表
                    ShopAttributeModel::updateById($id,
                        [
                            'isDeleted'    => 1,
                            'updatedByUid' => $rmsUserId
                        ]);

                    // 门店属性值关联表
                    ShopAttributeMappingModel::query()
                                             ->where('attributeId', $id)
                                             ->update(
                                                 [
                                                     'isDeleted'    => 1,
                                                     'updatedByUid' => $rmsUserId
                                                 ]);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('updateAttributeErr', [
                'id'        => $id,
                'data'      => $data,
                'rmsUserId' => $rmsUserId,
                'msg'       => $e->getMessage(),
            ]);
            throw new ShopException(ShopCodeEnum::ERR_DB_ERROR, '修改属性值失败');
        }

        return [];
    }


    /**
     * 获取门店属性
     * @param array $shopIds
     * @return array
     */
    public static function getShopAttribute(array $shopIds): array
    {
        $shopList = Shop::query()
                        ->whereIn('id', $shopIds)
                        ->select(['id', 'name', 'shopCode', 'addressPrefix'])
                        ->get()
                        ->keyBy('id')
                        ->toArray();
        if (!$shopList) {
            return [];
        }

        $data = $datas = [];
        ShopAttributeMappingModel::query()
                                 ->with(['shopAttributeMappingRel'])
                                 ->whereIn('shopId', $shopIds)
                                 ->get()
                                 ->map(function ($item) use (&$datas, $shopList) {
                                     $datas[$item->shopId]['addressPrefix'] = $shopList[$item->shopId]['addressPrefix'] ?? '';

                                     $categoryId = $item->shopAttributeMappingRel->categoryId ?? 0;
                                     if ($categoryId) {
                                         switch ($categoryId) {
                                             case ShopAttributeCategoryModel::CATEGORY_ID_12:// 门店状态 单选
                                             case ShopAttributeCategoryModel::CATEGORY_ID_13:// 迁址状态 单选
                                             case ShopAttributeCategoryModel::CATEGORY_ID_16:// 城市分级 单选
                                                 $datas[$item->shopId][$categoryId] = $item->shopAttributeMappingRel->name ?? '';
                                                 break;
                                             case ShopAttributeCategoryModel::CATEGORY_ID_1:// 门店性质 单选
                                             case ShopAttributeCategoryModel::CATEGORY_ID_2:// 店型 单选
                                             case ShopAttributeCategoryModel::CATEGORY_ID_5:// 选址场景分级 单选
                                             case ShopAttributeCategoryModel::CATEGORY_ID_6:// 点餐动线 单选
                                             case ShopAttributeCategoryModel::CATEGORY_ID_11:// 菜单等级 单选
                                             case ShopAttributeCategoryModel::CATEGORY_ID_14:// 收银设备 单选
                                                 $datas[$item->shopId][$categoryId] = $item->shopAttributeMappingRel->id ?? 0;
                                                 break;
                                             case ShopAttributeCategoryModel::CATEGORY_ID_3:// 选址场景 多选
                                             case ShopAttributeCategoryModel::CATEGORY_ID_4:// 售卖品类 多选
                                             case ShopAttributeCategoryModel::CATEGORY_ID_15:// 自定义标签 多选
                                                 $shopAttributeId = $item->shopAttributeMappingRel->id ?? 0;
                                                 if ($shopAttributeId) {
                                                     $datas[$item->shopId][$categoryId][] = $shopAttributeId;
                                                 }
                                                 break;
                                             case ShopAttributeCategoryModel::CATEGORY_ID_7:// 工程条件-展面 范围内输入值
                                             case ShopAttributeCategoryModel::CATEGORY_ID_8:// 工程条件-面积 范围内输入值
                                             case ShopAttributeCategoryModel::CATEGORY_ID_9:// 工程条件-进深 范围内输入值
                                             case ShopAttributeCategoryModel::CATEGORY_ID_10:// 工程条件-电量 范围内输入值
                                                 $datas[$item->shopId][$categoryId] = $item->value ?? '';
                                                 break;
                                         }
                                     }
                                 });

        foreach ($datas as $shopId => $v) {
            $data[$shopId]['shopId']                    = $shopId;
            $data[$shopId]['type']                      = $v[ShopAttributeCategoryModel::CATEGORY_ID_1] ?? '';// 门店性质
            $data[$shopId]['status']                    = $v[ShopAttributeCategoryModel::CATEGORY_ID_12] ?? '';// 门店状态
            $data[$shopId]['relocationStatus']          = $v[ShopAttributeCategoryModel::CATEGORY_ID_13] ?? '';// 迁址状态
            $data[$shopId]['shopType']                  = $v[ShopAttributeCategoryModel::CATEGORY_ID_2] ?? '';// 店型
            $data[$shopId]['addressPrefix']             = $v['addressPrefix'] ?? ''; // 城市
            $data[$shopId]['areaGrade']                 = $v[ShopAttributeCategoryModel::CATEGORY_ID_16] ?? '';// 城市分级
            $data[$shopId]['siteSelection']             = $v[ShopAttributeCategoryModel::CATEGORY_ID_3] ?? '';// 选址场景
            $data[$shopId]['siteSelectionGrade']        = $v[ShopAttributeCategoryModel::CATEGORY_ID_5] ?? '';// 场景等级
            $data[$shopId]['posLine']                   = $v[ShopAttributeCategoryModel::CATEGORY_ID_6] ?? '';// 点餐动线
            $data[$shopId]['engineeringExhibitionArea'] = $v[ShopAttributeCategoryModel::CATEGORY_ID_7] ?? '';// 工程条件-展面
            $data[$shopId]['engineeringArea']           = $v[ShopAttributeCategoryModel::CATEGORY_ID_8] ?? '';// 工程条件-面积
            $data[$shopId]['engineeringElectricity']    = $v[ShopAttributeCategoryModel::CATEGORY_ID_10] ?? '';// 工程条件-电量
            $data[$shopId]['engineeringDepth']          = $v[ShopAttributeCategoryModel::CATEGORY_ID_9] ?? '';// 工程条件-进深
            $data[$shopId]['menuLevel']                 = $v[ShopAttributeCategoryModel::CATEGORY_ID_11] ?? '';// 菜单等级
            $data[$shopId]['sellingCategory']           = $v[ShopAttributeCategoryModel::CATEGORY_ID_4] ?? '';// 售卖品类
            $data[$shopId]['posType']                   = $v[ShopAttributeCategoryModel::CATEGORY_ID_14] ?? '';// 收银设备
            $data[$shopId]['tags']                      = $v[ShopAttributeCategoryModel::CATEGORY_ID_15] ?? '';// 关联标签
        }
        return $data;
    }


    /**
     * 编辑门店属性
     * @param int $shopId
     * @param int $rmsUserId
     * @param array $data
     * @param int $isRms
     * @return array
     */
    public static function updateShopAttribute(int $shopId, int $rmsUserId, array $data, int $isRms = 0): array
    {
        $shopAttributeData = ShopAttributeMappingModel::query()
                                                      ->with(['shopAttributeMappingRel'])
                                                      ->where('shopId', $shopId)
                                                      ->get()
                                                      ->map(function ($item) {
                                                          $categoryId = $item->shopAttributeMappingRel->categoryId ?? 0;
                                                          $name       = $item->shopAttributeMappingRel->name ?? '';
                                                          $remark     = $item->shopAttributeMappingRel->remark ?? '';
                                                          return [
                                                              'id'          => $item->id,
                                                              'attributeId' => $item->attributeId,
                                                              'value'       => $item->value,
                                                              'categoryId'  => $categoryId,
                                                              'remark'      => $remark,
                                                              'name'        => $name,
                                                          ];
                                                      });

        // 门店属性修改 参数匹配
        $res = self::checkAttributeData($data, $shopAttributeData, $shopId, $rmsUserId);
        Log::info('updateShopAttribute', [
            'shopId'    => $shopId,
            'rmsUserId' => $rmsUserId,
            'data'      => $data,
            'oldData'   => $shopAttributeData,
            'res'       => $res,
        ]);

        // 数据统一处理
        DB::beginTransaction();
        try {
            if ($res['createData']) {
                ShopAttributeMappingModel::query()->insert($res['createData']);
            }
            if ($res['updateData']) {
                foreach ($res['updateData'] as $id => $updateData) {
                    ShopAttributeMappingModel::updateData($id, $updateData);
                }
            }
            if ($res['delIds']) {
                foreach ($res['delIds'] as $id) {
                    ShopAttributeMappingModel::updateData($id, [
                        'isDeleted'    => 1,
                        'updatedByUid' => $rmsUserId,
                    ]);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info('updateShopAttributeErr', [
                'shopId'    => $shopId,
                'rmsUserId' => $rmsUserId,
                'data'      => $data,
                'oldData'   => $shopAttributeData,
                'msg'       => $e->getMessage(),
            ]);
        }

        if ($isRms) {// rms后台更新门店属性通知
            (new \Kuafu\Nsq\NsqPublisher(config('nsq.default.address')))
                ->pub(NsqCodeEnum::SHOP_ATTRIBUTE_EVENT, [
                    'shopId' => $shopId,
                    'data'   => array_merge($data, $res['syncOpenShopData']),
                ]);
        }
        return [];
    }

    /**
     * 门店属性修改 参数匹配
     * @param array $data
     * @param $shopAttributeData
     * @param int $shopId
     * @param int $rmsUserId
     * @return array
     */
    public static function checkAttributeData(
        array $data,
        $shopAttributeData,
        int $shopId,
        int $rmsUserId
    ): array {
        $createData = [];
        $updateData = [];
        $delIds     = [];

        // 门店属性值列表
        $shopAttributeList = ShopAttributeModel::query()->get();

        // 同步到开店-选址表单的数据
        $syncOpenShopData = [];

        // 门店性质 单选 加盟店 直营店
        if (isset($data['type']) && strlen($data['type']) && $data['type'] != '0') {
            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_1)->first();
            if ($oldData) {
                if ($oldData['attributeId'] != $data['type']) {
                    $updateData[$oldData['id']] = [
                        'attributeId'  => $data['type'],
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            } else {
                $createData[] = [
                    'shopId'       => $shopId,
                    'attributeId'  => $data['type'],
                    'createdAt'    => time(),
                    'createdByUid' => $rmsUserId,
                    'value'        => '',
                ];
            }
        }

        // 门店状态 单选 选址中 筹备中 正常营业 暂停营业 闭店
        if (isset($data['status']) && strlen($data['status']) && $data['status'] != '0') {
            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_12)->first();
            if ($oldData) {
                if ($oldData['attributeId'] != $data['status']) {
                    $updateData[$oldData['id']] = [
                        'attributeId'  => $data['status'],
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            } else {
                $createData[] = [
                    'shopId'       => $shopId,
                    'attributeId'  => $data['status'],
                    'createdAt'    => time(),
                    'createdByUid' => $rmsUserId,
                    'value'        => '',
                ];
            }
        }

        // 店型 单选
        if (isset($data['shopType']) && strlen($data['shopType']) && $data['shopType'] != '0') {
            $syncOpenShopData['shopType'] = $data['shopType'];
            $oldData                      = $shopAttributeData->where('categoryId',
                ShopAttributeCategoryModel::CATEGORY_ID_2)->first();
            if ($oldData) {
                if ($oldData['attributeId'] != $data['shopType']) {
                    $updateData[$oldData['id']] = [
                        'attributeId'  => $data['shopType'],
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            } else {
                $createData[] = [
                    'shopId'       => $shopId,
                    'attributeId'  => $data['shopType'],
                    'createdAt'    => time(),
                    'createdByUid' => $rmsUserId,
                    'value'        => '',
                ];
            }
        }

        // 选址场景 多选
        if (isset($data['siteSelection'])) {
            $syncOpenShopData['siteSelection'] = $data['siteSelection'];

            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_3)
                                         ->keyBy('attributeId')->toArray();
            $newIds  = explode(',', $data['siteSelection']);
            foreach ($newIds as $v) {
                if ($oldData && isset($oldData[$v])) {
                    unset($oldData[$v]);
                } else {
                    $createData[] = [
                        'shopId'       => $shopId,
                        'attributeId'  => $v,
                        'createdAt'    => time(),
                        'createdByUid' => $rmsUserId,
                        'value'        => '',
                    ];
                }
            }
            if ($oldData) {
                $delIds = array_merge($delIds, array_column($oldData, 'id'));
            }
        }

        // 场景等级 单选
        if (isset($data['siteSelectionGrade']) && strlen($data['siteSelectionGrade']) && $data['siteSelectionGrade'] != '0') {
            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_5)->first();
            if ($oldData) {
                if ($oldData['attributeId'] != $data['siteSelectionGrade']) {
                    $updateData[$oldData['id']] = [
                        'attributeId'  => $data['siteSelectionGrade'],
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            } else {
                $createData[] = [
                    'shopId'       => $shopId,
                    'attributeId'  => $data['siteSelectionGrade'],
                    'createdAt'    => time(),
                    'createdByUid' => $rmsUserId,
                    'value'        => '',
                ];
            }
        }

        // 点餐动线 单选
        if (isset($data['posLine']) && strlen($data['posLine']) && $data['posLine'] != '0') {
            $syncOpenShopData['posLine'] = $data['posLine'];
            $oldData                     = $shopAttributeData->where('categoryId',
                ShopAttributeCategoryModel::CATEGORY_ID_6)->first();
            if ($oldData) {
                if ($oldData['attributeId'] != $data['posLine']) {
                    $updateData[$oldData['id']] = [
                        'attributeId'  => $data['posLine'],
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            } else {
                $createData[] = [
                    'shopId'       => $shopId,
                    'attributeId'  => $data['posLine'],
                    'createdAt'    => time(),
                    'createdByUid' => $rmsUserId,
                    'value'        => '',
                ];
            }
        }

        // 工程条件-展面 范围内输入值
        if (isset($data['engineeringExhibitionArea']) && strlen($data['engineeringExhibitionArea'])) {
            $syncOpenShopData['engineeringExhibitionArea'] = $data['engineeringExhibitionArea'];

            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_7)->first();
            $newId   = self::getShopAttributeByRange($shopAttributeList->toArray(),
                ShopAttributeCategoryModel::CATEGORY_ID_7, (int)$data['engineeringExhibitionArea']);

            if ($newId) {
                if ($oldData) {
                    if ($oldData['attributeId'] != $newId) {
                        $updateData[$oldData['id']] = [
                            'attributeId'  => $newId,
                            'value'        => $data['engineeringExhibitionArea'],
                            'updatedByUid' => $rmsUserId,
                        ];
                    } elseif ($oldData['value'] != $data['engineeringExhibitionArea']) {
                        $updateData[$oldData['id']] = [
                            'value'        => $data['engineeringExhibitionArea'],
                            'updatedByUid' => $rmsUserId,
                        ];
                    }
                } else {
                    $createData[] = [
                        'shopId'       => $shopId,
                        'value'        => $data['engineeringExhibitionArea'],
                        'attributeId'  => $newId,
                        'createdAt'    => time(),
                        'createdByUid' => $rmsUserId,
                    ];
                }
            }
        }

        // 工程条件-面积 范围内输入值
        if (isset($data['engineeringArea']) && strlen($data['engineeringArea'])) {
            $syncOpenShopData['engineeringArea'] = $data['engineeringArea'];

            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_8)->first();
            $newId   = self::getShopAttributeByRange($shopAttributeList->toArray(),
                ShopAttributeCategoryModel::CATEGORY_ID_8, (int)$data['engineeringArea']);
            if ($newId) {
                if ($oldData) {
                    if ($oldData['attributeId'] != $newId) {
                        $updateData[$oldData['id']] = [
                            'attributeId'  => $newId,
                            'value'        => $data['engineeringArea'],
                            'updatedByUid' => $rmsUserId,
                        ];
                    } elseif ($oldData['value'] != $data['engineeringArea']) {
                        $updateData[$oldData['id']] = [
                            'value'        => $data['engineeringArea'],
                            'updatedByUid' => $rmsUserId,
                        ];
                    }
                } else {
                    $createData[] = [
                        'shopId'       => $shopId,
                        'value'        => $data['engineeringArea'],
                        'attributeId'  => $newId,
                        'createdAt'    => time(),
                        'createdByUid' => $rmsUserId,
                    ];
                }
            }
        }

        // 工程条件-电量 范围内输入值
        if (isset($data['engineeringElectricity']) && strlen($data['engineeringElectricity'])) {
            $syncOpenShopData['engineeringElectricity'] = $data['engineeringElectricity'];

            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_10)->first();
            $newId   = self::getShopAttributeByRange($shopAttributeList->toArray(),
                ShopAttributeCategoryModel::CATEGORY_ID_10, (int)$data['engineeringElectricity']);

            if ($newId) {
                if ($oldData) {
                    if ($oldData['attributeId'] != $newId) {
                        $updateData[$oldData['id']] = [
                            'attributeId'  => $newId,
                            'value'        => $data['engineeringElectricity'],
                            'updatedByUid' => $rmsUserId,
                        ];
                    } elseif ($oldData['value'] != $data['engineeringElectricity']) {
                        $updateData[$oldData['id']] = [
                            'value'        => $data['engineeringElectricity'],
                            'updatedByUid' => $rmsUserId,
                        ];
                    }
                } else {
                    $createData[] = [
                        'shopId'       => $shopId,
                        'value'        => $data['engineeringElectricity'],
                        'attributeId'  => $newId,
                        'createdAt'    => time(),
                        'createdByUid' => $rmsUserId,
                    ];
                }
            }
        }

        // 工程条件-进深 范围内输入值
        if (isset($data['engineeringDepth']) && strlen($data['engineeringDepth'])) {
            $syncOpenShopData['engineeringDepth'] = $data['engineeringDepth'];

            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_9)->first();
            $newId   = self::getShopAttributeByRange($shopAttributeList->toArray(),
                ShopAttributeCategoryModel::CATEGORY_ID_9, (int)$data['engineeringDepth']);
            if ($newId) {
                if ($oldData) {
                    if ($oldData['attributeId'] != $newId) {
                        $updateData[$oldData['id']] = [
                            'attributeId'  => $newId,
                            'value'        => $data['engineeringDepth'],
                            'updatedByUid' => $rmsUserId,
                        ];
                    } elseif ($oldData['value'] != $data['engineeringDepth']) {
                        $updateData[$oldData['id']] = [
                            'value'        => $data['engineeringDepth'],
                            'updatedByUid' => $rmsUserId,
                        ];
                    }
                } else {
                    $createData[] = [
                        'shopId'       => $shopId,
                        'value'        => $data['engineeringDepth'],
                        'attributeId'  => $newId,
                        'createdAt'    => time(),
                        'createdByUid' => $rmsUserId,
                    ];
                }
            }
        }

        // 菜单等级 单选
        if (isset($data['menuLevel']) && strlen($data['menuLevel']) && $data['menuLevel'] != '0') {
            $syncOpenShopData['menuLevel'] = $data['menuLevel'];
            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_11)->first();
            if ($oldData) {
                if ($oldData['attributeId'] != $data['menuLevel']) {
                    $updateData[$oldData['id']] = [
                        'attributeId'  => $data['menuLevel'],
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            } else {
                $createData[] = [
                    'shopId'       => $shopId,
                    'attributeId'  => $data['menuLevel'],
                    'createdAt'    => time(),
                    'createdByUid' => $rmsUserId,
                    'value'        => '',
                ];
            }
        }

        // 售卖品类 多选
        if (isset($data['sellingCategory'])) {
            $syncOpenShopData['sellingCategory'] = $data['sellingCategory'];
            $oldData                             = $shopAttributeData->where('categoryId',
                ShopAttributeCategoryModel::CATEGORY_ID_4)
                                                                     ->keyBy('attributeId')->toArray();
            $newIds                              = explode(',', $data['sellingCategory']);
            foreach ($newIds as $v) {
                if ($oldData && isset($oldData[$v])) {
                    unset($oldData[$v]);
                } else {
                    $createData[] = [
                        'shopId'       => $shopId,
                        'attributeId'  => $v,
                        'createdAt'    => time(),
                        'createdByUid' => $rmsUserId,
                        'value'        => '',
                    ];
                }
            }
            if ($oldData) {
                $delIds = array_merge($delIds, array_column($oldData, 'id'));
            }
        }

        // 收银设备 单选
        if (isset($data['posType']) && strlen($data['posType']) && $data['posType'] != '0') {

            // 匹配tiger 选址表单的数据
            $shopPosType                     = $shopAttributeList
                ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_14)
                ->where('id', $data['posType'])
                ->first();
            $syncOpenShopData['posTypeEnum'] = $shopPosType->remark ?? 0;

            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_14)->first();
            if ($oldData) {
                if ($oldData['attributeId'] != $data['posType']) {
                    $updateData[$oldData['id']] = [
                        'attributeId'  => $data['posType'],
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            } else {
                $createData[] = [
                    'shopId'       => $shopId,
                    'attributeId'  => $data['posType'],
                    'createdAt'    => time(),
                    'createdByUid' => $rmsUserId,
                    'value'        => '',
                ];
            }
        }

        // 关联标签 多选
        if (isset($data['tags'])) {
            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_15)
                                         ->keyBy('attributeId')->toArray();
            $newIds  = explode(',', $data['tags']);
            foreach ($newIds as $v) {
                if ($oldData && isset($oldData[$v])) {
                    unset($oldData[$v]);
                } else {
                    $createData[] = [
                        'shopId'       => $shopId,
                        'attributeId'  => $v,
                        'createdAt'    => time(),
                        'createdByUid' => $rmsUserId,
                        'value'        => '',
                    ];
                }
            }
            if ($oldData) {
                $delIds = array_merge($delIds, array_column($oldData, 'id'));
            }
        }

        // 城市分级 单选
        if (isset($data['areaGrade']) && strlen($data['areaGrade']) && $data['areaGrade'] != '0') {
            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_16)->first();
            if ($oldData) {
                if ($oldData['attributeId'] != $data['areaGrade']) {
                    $updateData[$oldData['id']] = [
                        'attributeId'  => $data['areaGrade'],
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            } else {
                $createData[] = [
                    'shopId'       => $shopId,
                    'attributeId'  => $data['areaGrade'],
                    'createdAt'    => time(),
                    'createdByUid' => $rmsUserId,
                    'value'        => '',
                ];
            }
        }

        // 城市code 单选
        if (isset($data['cityCode']) && strlen($data['cityCode']) && $data['cityCode'] != '0') {
            $attribute = $shopAttributeList->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_17)
                                           ->first();
            $oldData   = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_17)->first();
            if ($oldData) {
                if ($oldData['value'] != $data['cityCode']) {
                    $updateData[$oldData['id']] = [
                        'value'        => $data['cityCode'],
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            } else {
                $createData[] = [
                    'shopId'       => $shopId,
                    'attributeId'  => $attribute->id ?? 0,
                    'createdAt'    => time(),
                    'createdByUid' => $rmsUserId,
                    'value'        => $data['cityCode'],
                ];
            }
        }

        // 迁址状态 单选 是 否
        if (isset($data['relocationStatus']) && $data['relocationStatus']) {
            if (in_array($data['relocationStatus'], [1, 2])) {
                $data['relocationStatus'] = $data['relocationStatus'] == 1 ? '是' : '否';
                $shopAttributeTem         = $shopAttributeList
                    ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_13)
                    ->where('name', $data['relocationStatus'])
                    ->first();
                $data['relocationStatus'] = $shopAttributeTem->id ?? 0;
            }
            $oldData = $shopAttributeData->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_13)->first();
            if ($oldData) {
                if ($oldData['attributeId'] != $data['relocationStatus']) {
                    $updateData[$oldData['id']] = [
                        'attributeId'  => $data['relocationStatus'],
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            } else {
                $createData[] = [
                    'shopId'       => $shopId,
                    'attributeId'  => $data['relocationStatus'],
                    'createdAt'    => time(),
                    'createdByUid' => $rmsUserId,
                    'value'        => '',
                ];
            }
        }
        return [
            'createData'       => $createData,
            'updateData'       => $updateData,
            'delIds'           => $delIds,
            'syncOpenShopData' => $syncOpenShopData,
        ];
    }

    /**
     * 门店筛选通过门店属性
     * @param string $name
     * @param array $data
     * @return array
     */
    public static function getShopByAttributeSearch(string $name, array $data): array
    {
        $shopList = [];
        if ($name) {// 门店编号/门店名称搜索
            $name = str_replace('，', ',', $name);
            $name = explode(',', $name);
            if (!$name) {
                return $shopList;
            }
            $shopList = Shop::query()
                            ->when($name, function ($query) use ($name) {
                                $query->where(function ($query) use ($name) {
                                    foreach ($name as $k => $v) {
                                        if ($k >= 5) {
                                            break;
                                        }
                                        $query->orWhere('name', 'like', "%{$v}%");
                                        if (is_numeric($v)) {
                                            $query->orWhere('shopCode', $v);
                                        }
                                    }
                                });
                            })
                            ->select(['id', 'shopCode', 'name'])
                            ->get()
                            ->toArray();
            return $shopList;
        }
        if (!$data['list']) {
            return $shopList;
        }
        $sqlArr = $shopIds = [];
        $sqlRaw = '';
        foreach ($data['list'] as $v) {
            $value = explode(',', $v['value']) ?? [];
            if (!$v['value'] || !$v['key'] || !$value) {
                continue;
            }
            switch ($v['key']) {
                case ShopAttributeCategoryModel::CATEGORY_ID_1:// 门店性质
                case ShopAttributeCategoryModel::CATEGORY_ID_12:// 门店状态
                case ShopAttributeCategoryModel::CATEGORY_ID_2:// 店型
                case ShopAttributeCategoryModel::CATEGORY_ID_13:// 迁址状态
                case ShopAttributeCategoryModel::CATEGORY_ID_5:// 场景等级
                case ShopAttributeCategoryModel::CATEGORY_ID_6:// 点餐动线
                case ShopAttributeCategoryModel::CATEGORY_ID_11:// 菜单等级
                case ShopAttributeCategoryModel::CATEGORY_ID_14:// 收银设备
                case ShopAttributeCategoryModel::CATEGORY_ID_7:// 工程条件-展面
                case ShopAttributeCategoryModel::CATEGORY_ID_8:// 工程条件-面积
                case ShopAttributeCategoryModel::CATEGORY_ID_10:// 工程条件-电量
                case ShopAttributeCategoryModel::CATEGORY_ID_9:// 工程条件-进深
                case ShopAttributeCategoryModel::CATEGORY_ID_16:// 城市分级
                    if (count($value) == 1) {
                        $sqlRaw = ' attributeId = ' . $value[0];
                    } else {
                        if ($v['condition'] == ShopAttributeMappingModel::SEARCH_ANY) {
                            $sqlRaw = ' attributeId in (' . implode(',', $value) . ')';
                        } else {
                            $sqlRaw = ' id=0 ';// 单选类型 选 满足所有条件即不会显现结果
                        }
                    }

                    if ($data['condition'] == ShopAttributeMappingModel::SEARCH_ALL) {
                        $shopIds[$v['key']] = ShopAttributeMappingModel::query()
                                                                       ->whereRaw($sqlRaw)
                                                                       ->groupBy('shopId')
                                                                       ->pluck('shopId')
                                                                       ->toArray();
                    } else {
                        $sqlArr[] = $sqlRaw;
                    }
                    break;
                case ShopAttributeCategoryModel::CATEGORY_ID_3:// 选址场景
                case ShopAttributeCategoryModel::CATEGORY_ID_4:// 售卖品类
                case ShopAttributeCategoryModel::CATEGORY_ID_15:// 关联标签
                    if (count($value) == 1) {
                        $sqlRaw = ' attributeId = ' . $value[0];
                    } else {
                        if ($v['condition'] == ShopAttributeMappingModel::SEARCH_ANY) {
                            $sqlRaw = ' attributeId in (' . implode(',', $value) . ')';
                        } else {
                            foreach ($value as $vv) {
                                $sqlRaw = ' attributeId= ' . $vv;// 多选类型
                            }
                        }
                    }
                    if ($data['condition'] == ShopAttributeMappingModel::SEARCH_ALL) {
                        $shopIds[$v['key']] = ShopAttributeMappingModel::query()
                                                                       ->whereRaw($sqlRaw)
                                                                       ->groupBy('shopId')
                                                                       ->pluck('shopId')
                                                                       ->toArray();
                    } else {
                        $sqlArr[] = $sqlRaw;
                    }
                    break;
                case ShopAttributeCategoryModel::CATEGORY_ID_17:// 城市 cityCode
                    $shopAttributeCityId = ShopAttributeModel::query()
                                                             ->where('categoryId',
                                                                 ShopAttributeCategoryModel::CATEGORY_ID_17)
                                                             ->value('id');
                    if (count($value) == 1) {
                        $sqlRaw = ' attributeId = ' . $shopAttributeCityId . ' and value=' . $value[0];
                    } else {
                        if ($v['condition'] == ShopAttributeMappingModel::SEARCH_ANY) {
                            $sqlRaw = ' attributeId = ' . $shopAttributeCityId . ' and value in (' . implode(',',
                                    $value) . ')';
                        } else {
                            foreach ($value as $vv) {
                                $sqlRaw = ' attributeId = ' . $shopAttributeCityId . ' and value= ' . $vv;// 多选类型
                            }
                        }
                    }
                    if ($data['condition'] == ShopAttributeMappingModel::SEARCH_ALL) {
                        $shopIds[$v['key']] = ShopAttributeMappingModel::query()
                                                                       ->whereRaw($sqlRaw)
                                                                       ->groupBy('shopId')
                                                                       ->pluck('shopId')
                                                                       ->toArray();
                    } else {
                        $sqlArr[] = $sqlRaw;
                    }
                    break;
            }
        }
        $getAttributeShopIds = [];
        if ($data['condition'] == ShopAttributeMappingModel::SEARCH_ALL && $shopIds) {// 组合查询 满足所有条件 and
            $getAttributeShopIds = ShopAttributeMappingModel::query()
                                                            ->when($shopIds, function ($query) use ($shopIds) {
                                                                foreach ($shopIds as $v) {
                                                                    $query->whereIn('shopId', $v);
                                                                }
                                                            })
                                                            ->groupBy('shopId')
                                                            ->pluck('shopId')
                                                            ->toArray();
            unset($shopIds);
        } elseif ($data['condition'] == ShopAttributeMappingModel::SEARCH_ANY && $sqlArr) {// 单个条件满足其中一个 or
            $getAttributeShopIds = ShopAttributeMappingModel::query()
                                                            ->when($sqlArr, function ($query) use ($sqlArr) {
                                                                foreach ($sqlArr as $sql) {
                                                                    $query->orWhereRaw(DB::raw($sql));
                                                                }
                                                            })
                                                            ->groupBy('shopId')
                                                            ->pluck('shopId')
                                                            ->toArray();
            unset($sqlArr);
        }
        if ($getAttributeShopIds) {
            $shopList = Shop::query()->find($getAttributeShopIds, ['id', 'shopCode', 'name'])->toArray();
        }
        return $shopList;
    }

    /**
     * 门店档案修改门店属性值
     * @param int $shopId
     * @param array $updateShopAttribute
     */
    public static function updateShopAttributeByShopEdit(int $shopId, array $updateShopAttribute)
    {
        $update = [];
        if (isset($updateShopAttribute['type'])) {// 店铺类型-门店性质
            $update['type'] = $updateShopAttribute['type'];
        }
        if (isset($updateShopAttribute['city'])) {
            $update['cityCode'] = $updateShopAttribute['city'];

            // 门店属性值列表
            $shopAttributeList = ShopAttributeModel::query()
                                                   ->where('categoryId', [
                                                       ShopAttributeCategoryModel::CATEGORY_ID_16,
                                                       ShopAttributeCategoryModel::CATEGORY_ID_11
                                                   ])
                                                   ->get();
            // 城市分级  单选 一线 二线 三线 四线 五线
            $cityGradeAttributeData = $shopAttributeList
                ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_16)->values()
                ->toArray();

            // 菜单等级 单选 A级(一线+西藏) B级(新一/二/三线城市) C级(四/五线) S级(精选产品特殊定价) 其他
            $cityMenuLevelAttributeData = $shopAttributeList
                ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_11)->values()
                ->toArray();

            $cityData = AreaModel::query()
                                 ->where('areaId', $updateShopAttribute['city'])
                                 ->where('level', AreaCodeEnum::AREA_CITY)->first();
            // 城市分级
            $cityGrade                        = $cityData->grade ?? 0;// 城市分级
            $update['areaGrade'] = $cityGradeAttributeData[$cityGrade - 1]['id'] ?? 0;

            // 菜单等级
            $cityMenuLevel                    = self::getMenuLevel($cityData->menuLevel ?? '');
            $update['menuLevel'] = $cityMenuLevelAttributeData[$cityMenuLevel - 1]['id'] ?? 0;
        }
        if ($update) {
            self::updateShopAttribute($shopId, 0, $update);
        }
    }

    /**
     * 城市对应菜单等级
     * @param $menuLevel
     * @return int
     */
    public static function getMenuLevel($menuLevel): int
    {
        return [
                'A' => 1,
                'B' => 2,
                'C' => 3,
            ][$menuLevel] ?? 0;
    }

    /**
     * tiger open_shop_site_locations caseRegisterType对应rms门店属性 收银设备 值 1-夸父收银 2-商场收银 3-美团收银
     * @param $cashType
     */
    public static function getPosType($cashType)
    {
        $shopAttribute   = ShopAttributeModel::query()
                                             ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_14)
                                             ->where('remark', $cashType)
                                             ->first();
        return $shopAttribute->id ?? 0;
    }

    /**
     * 获取门店阶段状态属性值
     * @param string $shopStatusText
     * @return int
     */
    public static function getShopStatusByText(string $shopStatusText): int
    {
        $shopAttribute = ShopAttributeModel::query()
                                           ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_12)
                                           ->where('name', $shopStatusText)
                                           ->first();
        return $shopAttribute->id ?? 0;
    }

    /**
     * 新建门店初始化门店属性
     * @param array $shop
     */
    public static function createShopAttribute(array $shop)
    {
        // 门店属性值列表
        $shopAttributeList = ShopAttributeModel::query()->get();

        // 城市分级  单选 一线 二线 三线 四线 五线
        $cityGradeAttributeData = $shopAttributeList
            ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_16)->values()
            ->toArray();

        // 菜单等级 单选 A级(一线+西藏) B级(新一/二/三线城市) C级(四/五线) S级(精选产品特殊定价) 其他
        $cityMenuLevelAttributeData = $shopAttributeList
            ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_11)->values()
            ->toArray();

        // 城市对应
        $areaData   = AreaModel::query()
                               ->where('areaId', $shop['city'])
                               ->where('level', AreaCodeEnum::AREA_CITY)
                               ->first();
        $createData = [];
        $attributeId = $shop['type'] ?? 0;// 门店性质 单选 加盟店 直营店
        if ($attributeId) {
            $createData[] = [
                'shopId'      => $shop['id'],
                'attributeId' => $attributeId,
                'value'       => '',
                'createdAt'   => time(),
            ];
        }
        $city = $shop['city'] ?? 0;// 城市code
        if ($city) {
            $categoryId   = ShopAttributeCategoryModel::CATEGORY_ID_17;// 城市
            $attribute    = $shopAttributeList->where('categoryId', $categoryId)->first();
            $createData[] = [
                'shopId'      => $shop['id'],
                'attributeId' => $attribute->id,
                'value'       => $city,
                'createdAt'   => time(),
            ];

            // 城市分级
            $cityGrade = $areaData[$city]['grade'] ?? 0;// 城市分级
            $newId     = $cityGradeAttributeData[$cityGrade - 1]['id'] ?? 0;
            if ($newId) {
                $createData[] = [
                    'shopId'      => $shop['id'],
                    'attributeId' => $newId,
                    'value'       => '',
                    'createdAt'   => time(),
                ];
            }

            // 菜单等级
            $cityMenuLevel = self::getMenuLevel($areaData[$city]['menuLevel'] ?? '');// 菜单等级
            $newId         = $cityMenuLevelAttributeData[$cityMenuLevel - 1]['id'] ?? 0;
            if ($newId) {
                $createData[] = [
                    'shopId'      => $shop['id'],
                    'attributeId' => $newId,
                    'value'       => '',
                    'createdAt'   => time(),
                ];
            }
        }

        // 门店状态 单选 选址中 筹备中 正常营业 暂停营业 闭店
        $shopStatus = $shopAttributeList->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_12)->first();
        if ($shopStatus) {
            $createData[] = [
                'shopId'      => $shop['id'],
                'attributeId' => $shopStatus->id,
                'value'       => '',
                'createdAt'   => time(),
            ];
        }

        // 门店性质 单选 加盟店 直营店
        $shopType = $shopAttributeList->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_1)->first();
        if ($shopType) {
            $createData[] = [
                'shopId'      => $shop['id'],
                'attributeId' => $shopType->id,
                'value'       => '',
                'createdAt'   => time(),
            ];
        }

        // 迁址状态  单选 是 or 否
        $relocationStatus = $shopAttributeList
            ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_13)
            ->where('name', '否')->first();
        if ($relocationStatus) {
            $createData[] = [
                'shopId'      => $shop['id'],
                'attributeId' => $relocationStatus->id,
                'value'       => '',
                'createdAt'   => time(),
            ];
        }
        if ($createData) {
            ShopAttributeMappingModel::query()->insert($createData);
        }
    }

    /**
     * 工程条件 范围值对应属性id
     * @param array $shopAttributeList
     * @param int $categoryId
     * @param int $value
     * @return int
     */
    public static function getShopAttributeByRange(array $shopAttributeList, int $categoryId, int $value): int
    {
        $newId = 0;
        collect($shopAttributeList)->where('categoryId', $categoryId)
                                   ->map(function ($item) use ($categoryId, $value, &$newId) {
                                       if (strpos($item['remark'], ',') !== false) {
                                           $remark = json_decode($item['remark'], true);
                                           if ($categoryId == ShopAttributeCategoryModel::CATEGORY_ID_8) {
                                               if ($value >= $remark[0] && $value <= $remark[1]) {
                                                   $newId = $item['id'];
                                               }
                                           } else {
                                               if ($value >= $remark[0] && $value < $remark[1]) {
                                                   $newId = $item['id'];
                                               }
                                           }
                                       } else {
                                           if ($categoryId == ShopAttributeCategoryModel::CATEGORY_ID_8) {
                                               if ($value > $item['remark']) {
                                                   $newId = $item['id'];
                                               }
                                           } else {
                                               if ($value >= $item['remark']) {
                                                   $newId = $item['id'];
                                               }
                                           }
                                       }
                                   });
        return $newId;
    }
}
